-------------------------------------------------------------------------------------
-- -*- coding: utf-8 -*-
--
-- @author:   zxf
-- @email:    07291@qq.com
-- @date:     2024/8/23
-- @module:   property_base
-- @describe:
-- @version:  v1.0
--

-------------------------------------------------------------------------------------

---@class property_base
local property_base = {}
property_base.value = nil
property_base.addCall = nil

function property_base:set_value(val, mustCall)
    if self:set_value_no_call(val) or mustCall then
        self:call()
    end
end

function property_base:get_value()
    return self.value
end

function property_base:set_value_no_call(val)
    if self.value == val then
        return false
    end
    self.value = val
    return true
end

function property_base:add_listen_no_call(call)
    if not self.addCall then
        self.addCall = {}
    end
    for i, v in ipairs(self.addCall) do
        if v == call then
            return false
        end
    end
    table.insert(self.addCall, call)
    return true
end

function property_base:add_listen(call)
    self:add_listen_no_call(call)
    self:call()
end

function property_base:call()
    if self.addCall then
        for i, v in ipairs(self.addCall) do
            v(self.value)
        end
    end
end

function property_base:remove_listen(call)
    if not self.addCall then
        return false
    end
    for i, v in ipairs(self.addCall) do
        if v == call then
            table.remove(self.addCall, i)
            return true
        end
    end
    return false
end

function property_base:new(val)
    local ret = {}
    self.__index = self
    self.value = val
    setmetatable(ret, self)
    return ret
end

return property_base